package cs9322.assign3.operation;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;

import cs9322.assign3.model.Order;
import cs9322.assign3.model.Payment;

/**
 * Servlet implementation class PayOrder
 */
public class PayOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PayOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String oid = request.getParameter("oid");
		String type = request.getParameter("type");
		String amount = request.getParameter("amount");
		String detail = request.getParameter("detail");
		ClientConfig clientConfig = new DefaultClientConfig();
		Client client = Client.create(clientConfig);
		WebResource service = client.resource("http://localhost:8080/cs9322.assign3.coffee");
		Order o = service.path("starbucks").path("orders/"+oid).accept(MediaType.TEXT_XML).get( Order.class);
		o.setPaid(true);
		service.path("starbucks").path("orders/"+oid).type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML)
		   .put(ClientResponse.class, o);
		
		Form form = new Form();
		form.add("oid", oid);
		form.add("type", type);
		form.add("amount", amount);
		form.add("detail", detail);
		
		ClientResponse cr = service.path("starbucks").path("payments").type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.TEXT_XML)
				   .put(ClientResponse.class, form);
		Payment payment = cr.getEntity(Payment.class);
		request.setAttribute("payment", payment);
		request.setAttribute("response", cr);
		request.getRequestDispatcher("paymentgenerated.jsp").forward(request, response);
		
		
	}

}
